package com.mall.user.serviceImpl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.common.constant.ActiveStatusEnum;
import com.mall.user.constant.UserServiceEnum;
import com.mall.user.dto.bo.resp.UserResp;
import com.mall.user.dto.entity.TbMember;
import com.mall.user.dto.model.LoginModel;
import com.mall.user.dto.vo.UserVo;
import com.mall.user.mapper.TbMemberMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.user.service.TbMemberService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import utils.JwtTokenUtils;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xrj
 * @since 2022-04-30
 */
@Slf4j
@Service
@Component
public class TbMemberServiceImpl extends ServiceImpl<TbMemberMapper, TbMember> implements TbMemberService {

    @Override
    public UserResp login(UserVo userVo) {
        String plain = userVo.getUserPwd();
        String encodePwd = DigestUtil.md5Hex(plain.getBytes(StandardCharsets.UTF_8));
        QueryWrapper<TbMember> qw = new QueryWrapper<>();
        qw.eq("userName",userVo.getUserName());
        UserResp resp = new UserResp();
        LoginModel loginModel = new LoginModel();
        resp.setLoginModel(loginModel);
        TbMember user = getOne(qw);
        if (user == null){
            resp.setCode(UserServiceEnum.USER_NO_EXIST.getCode());
            resp.setMsg(UserServiceEnum.USER_NO_EXIST.getMsg());
            return resp;
        }
        if (!user.getPassword().equals(encodePwd)){
            resp.setCode(UserServiceEnum.PWD_ERROR.getCode());
            resp.setMsg(UserServiceEnum.PWD_ERROR.getMsg());
            return resp;
        }
        if (!ActiveStatusEnum.ACTIVATED.getCode().equals(user.getIsverified())){
            resp.setCode(UserServiceEnum.ACCOUNT_NO_ACTIVE.getCode());
            resp.setMsg(UserServiceEnum.ACCOUNT_NO_ACTIVE.getMsg());
            return resp;
        }
        //设置token
        try {
            BeanUtils.copyProperties(user,loginModel);
            String token = JwtTokenUtils.creatJwtToken(JSON.toJSONString(user));
            loginModel.setToken(token);
        } catch (Exception e) {
            resp.setCode(UserServiceEnum.TOKEN_CREATE_ERROR.getCode());
            resp.setCode(UserServiceEnum.TOKEN_CREATE_ERROR.getMsg());
            return resp;
        }
        log.info("用户:{},登录成功!",user.getUsername());
        resp.setCode(UserServiceEnum.SUCCESS.getCode());
        resp.setMsg(UserServiceEnum.SUCCESS.getMsg());
        return resp;
    }
}
